<?php
namespace app\api\logic;

use think\db;
use app\api\weixin\logic;
/**
 * @author YangPan
 *
 * 创建订单参数说明：
 *      - status_logic 1:购买虚拟商品，修改过期日期
 *
 *
 */
class Order extends Base {
    protected $page;            # 分页参数
    protected $timeStamp;       # 当前时间戳
    protected $signKey;         # KEY值
    protected $cacheDb;         # 数据库缓存时间

    public function __construct()
    {
        $this->page = 30;
        $this->timeStamp = time();
        $this->signKey = config('custom.signKey');
        $this->cacheDb = 1200;    
    }

    public function index()
    {
        return '';
    }


    /**
     * 批量增加购物车
     * @param array $info
     *      - admin_id      number      管理者ID
     *      - user_id       number      用户ID
     *      - goods_id      number      商品ID
     *      - numbs         number      商品数量
     *
     * @return json
     */
    public function addListCart($info)
    {
        $data['admin_id'] = $info['admin_id'];
        $data['user_id'] = $info['user_id'];
        //循环添加商品
        foreach ($info['shop'] as $v) {
            $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'goods_id' => $v['goods_id'], 'param' => $v['param']];
            $res = db('order_cart')->where($where)->find();

            $info['create_time'] = $this->timeStamp;

            $v['numbs'] = $v['numbs'] > 0 ? $v['numbs'] : 1;

            // 如果存在就加，不存在就增加
            if ($res) {
                $res = db('order_cart')->where(['id' => $res['id']])->setInc('numbs', $v['numbs']);

                if ($res < 1) {
                    err('', 'ADD CART FAIL');
                }
            } else {
                $data['create_time'] = $this->timeStamp;
                $data['param'] = $v['param'];
                $data['goods_id'] = $v['goods_id'];
                $data['numbs'] = $v['numbs'];
                $res = db('order_cart')->insert($data);

                if ($res < 1) {
                    err('', 'ADD CART FAIL');
                }
            }
        }
        suc();
    }

    //设置默认地址
    public function upAddr($info)
    {
        // 其它地址设置为非默认
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id']];
        db('order_address')->where($where)->update(['is_default' => 0]);
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'id' => $info['id']];
        $res = db('order_address')->where($where)->update(['is_default' => 1]);
        if ($res < 1) {
            err('', 'ADD ADDRESS FAIL');
        }

        suc();
    }

    /**
     * 确认订单 - 地址需要获取的信息
     *      1. 获取默认地址
     *      2. 更新购物车商品状态
     *      3. 发票信息 - 暂时不开发
     *      4. 配送方式 - 暂时不开发
     *
     * @param array $info
     *      - admin_id      number      管理者ID
     *      - user_id       number      用户ID
     *      - cart_ids      string      商品信息 - 5612,5613
     *
     * @return json
     */
    public function confirmOrder($info)
    {
        //$info['cart_ids'] = '5612,5613';

        # 计算商品总价
        $field = 'c.id, c.numbs, g.title, g.subtitle, g.thumb, g.price, c.param';
        $where = ['c.id' => ['in', $info['cart_ids']], 'c.user_id' => $info['user_id']];
        $goods = db('order_cart')->alias('c')->join('goods g', 'c.goods_id = g.id')->field($field)->where($where)->select();
        
        $total_fee = 0;
        $total_fee_attr = 0;
        
        # 获取商品总价格
        foreach ($goods as $key => $value) {
            $resAttr = db('goods_attr')->field('id, name, price, stock')->where(['id'=>['in', $value['param']]])->select();
    
            // 当前商品的属性总价格
            $this_attr_total_fee = 0;
            
            // 计算规格的累加价格
            foreach ($resAttr as $val) {
                $total_fee_attr += $val['price'];
                $this_attr_total_fee += $val['price'];
            }
            
            $goods[$key]['goods_attr'] = $resAttr;                  // 当前商品的所有属性
            $goods[$key]['total_fee_attr'] = $this_attr_total_fee;  // 当前商品属性总价格
            $total_fee += $value['price'] + $total_fee_attr;
        }
        
        $total_fee = sprintf('%.2f', $total_fee);
        
        # 获取默认地址
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'is_default' => 1];
        $addr = db('order_address')->where($where)->field('admin_id, user_id', true)->find();

        # 计算运费
        $freight = db('freight')->where(['admin_id' => $info['admin_id']])->select();

        $fee = 0;
        foreach ($freight as $value) {
            if ($total_fee > $value['min'] and $total_fee < $value['max']) {
                $fee = $value['fee'];
            }
        }
        $fee = sprintf('%.2f', $fee);

        # 返回的数据
        $data = [];
        $data['total_fee'] = $total_fee;
        $data['freight_fee'] = $fee;
        $data['pay_type'] = 2;
        $data['addr'] = $addr;
        $data['goods'] = $goods;
        suc($data);
    }

    /**
     * 创建订单 - 虚拟商品 (没有购物车，没有订单商品表)
     *
     * @param array $info
     *      - admin_id          number      管理者ID
     *      - user_id           number      用户ID
     *      - dues_id           number      会费列表ID
     *      - subject           string      支付标题
     *      - type              number      支付类型
     *      - delivery_amount   float       快递金额
     *      - addr_name         string      收货人
     *      - addr_mobile       string      收货电话
     *      - addr_detail       string      收货地址详细
     *      - invoice_tax       float       发票税率
     *      - invoice_title     string      发票抬头
     *      - invoice_content   string      发票内容
     *
     * @return json
     */
    public function createOrderVirtual($info)
    {
        // 查询会费ID是否存在
        $res = db('dues')->where(['id' => $info['dues_id']])->find();
        if (empty($res)) {
            err('', 'PARAM ERROR');
        }

        // 总价
        $info['amount'] = $res['price'] * $info['quantity'];

        // 插入到数据库的数据
        $data = [];
        $data['admin_id'] = $info['admin_id'];
        $data['user_id'] = $info['user_id'];
        $data['amount'] = $info['amount'];                       // 总价
        $data['subject'] = $info['subject'];                     // 订单标题
        $data['quantity'] = $info['quantity'];                   // 购买的数量
        $data['message'] = isset($info['message']) ? $info['message'] : ' ';                     // 卖家留言
        $data['status_logic'] = 1;                                   // 此参数用于判断回调函数应该怎样处理业务逻辑
        // 1:购买虚拟商品，修改过期日期

        // 用于微信支付回调函数，处理用户过期日期                                                  
        $param = [
            'dues_id' => $info['dues_id'],
            'numbs' => $res['numbs'],
            'unit' => $res['unit'],
        ];
        $data['param'] = json_encode($param);

        /* 
        $data['delivery_amount'] = $info['delivery_amount'];     // 快递金额
        $data['addr_name'] = $info['addr_name'];                 // 收货人
        $data['addr_mobile'] = $info['addr_mobile'];             // 收货电话
        $data['addr_detail'] = $info['addr_detail'];             // 收货地址详细
        
        $data['invoice_tax'] = $info['invoice_tax'];             // 发票税率
        $data['invoice_title'] = $info['invoice_title'];         // 发票抬头
        $data['invoice_content'] = $info['invoice_content'];     // 发票内容
         */

        // 创建订单
        $weixin = new Weixin();
        $res = $weixin->unifiedOrder($data);
        suc($res);
    }

    /**
     * 创建订单 - 为什么不传地址ID，因为有可能是从微信获取地址信息
     *      1. 数据写入订单表
     *      2. 清空购物车
     *      3. 商品写入订单商品表
     *
     * @param array $info
     *      - admin_id          number      管理者ID
     *      - user_id           number      用户ID
     *      - cart_ids          string      购物车ids (1234,1235,1236)
     *      - pay_type          number      支付类型
     *      - addr_name         string      收货人
     *      - addr_mobile       string      收货电话
     *      - addr_detail       string      收货地址详细
     *      - invoice_tax       float       发票税率
     *      - invoice_title     string      发票抬头
     *      - invoice_content   string      发票内容
     *
     * @return json
     */
    public function createOrder($info)
    {
        # 计算商品总价
        $field = 'c.id, c.numbs, g.title, g.subtitle, g.thumb, g.price, c.param';
        $where = ['c.id' => ['in', $info['cart_ids']], 'c.user_id' => $info['user_id']];
        $goods = db('order_cart')->alias('c')->join('goods g', 'c.goods_id = g.id')->field($field)->where($where)->select();
        
        $total_fee = 0;
        $total_fee_attr = 0;
        $insert_data = [];
        
        # 获取商品总价格
        foreach ($goods as $key => $value) {
            $resAttr = db('goods_attr')->field('name, price')->where(['id'=>['in', $value['param']]])->select();
    
            // 计算规格的累加价格
            foreach ($resAttr as $val) {
                $total_fee_attr += $val['price'];
            }
            
            $total_fee += $value['price'] + $total_fee_attr;
            
            # 写入订单商品表中的数据
            //$insert_data[$key]['shops_id'] = $value['shops_id'];
            $insert_data[$key]['admin_id'] = $info['admin_id'];
            $insert_data[$key]['user_id'] = $info['user_id'];
            $insert_data[$key]['goods_id'] = $value['id'];
            $insert_data[$key]['title'] = $value['title'];
            $insert_data[$key]['subtitle'] = $value['subtitle'];
            $insert_data[$key]['thumb'] = $value['thumb'];
            $insert_data[$key]['price'] = $value['price'];
            $insert_data[$key]['numbs'] = $value['numbs'];
            $insert_data[$key]['create_time'] = $this->timeStamp;
            $insert_data[$key]['status'] = 0;
            $insert_data[$key]['param'] = json_encode($resAttr);
        }
        
        $total_fee = sprintf('%.2f', $total_fee);

        # 计算运费
        $freight = db('freight')->where(['admin_id' => $info['admin_id']])->select();

        $fee = 0;
        foreach ($freight as $value) {
            if ($total_fee > $value['min'] and $total_fee < $value['max']) {
                $fee = $value['fee'];
            }
        }
        $fee = sprintf('%.2f', $fee);

        # 创建订单 - 订单参数
        $data = [];
        $data['genre'] = 'goods';
        $data['subject'] = '商品支付 - ' . $info['user_id'];      // 支付标题
        $data['admin_id'] = $info['admin_id'];
        $data['user_id'] = $info['user_id'];
        $data['type'] = $info['pay_type'];                       // 1：货到付款，2：微信支付，3：支付宝支付
        $data['amount'] = $total_fee + $fee;                     // 总价
        $data['delivery_amount'] = $fee;                         // 快递金额
        $data['addr_name'] = $info['addr_name'];                 // 收货人
        $data['addr_mobile'] = $info['addr_mobile'];             // 收货电话
        $data['addr_detail'] = $info['addr_detail'];             // 收货地址详细
        $data['message'] = $info['message'];                     // 卖家留言
        //$data['invoice_tax'] = $info['invoice_tax'];             // 发票税率
        //$data['invoice_title'] = $info['invoice_title'];         // 发票抬头
        //$data['invoice_content'] = $info['invoice_content'];     // 发票内容

        // 用于回调逻辑判断
        $param = [
            'type' => 'goods'
        ];
        $data['param'] = json_encode($param);

        // 创建订单
        $weixin = new Weixin();
        $res = $weixin->unifiedOrder($data);
        
        # 订单商品表写入商品 - 不能在notify中加入
        foreach ($insert_data as $key => $value) {
            $insert_data[$key]['order_id'] = $res['orderId'];
        }

        // 购物车物品写入商品表
        db('order_goods')->insertAll($insert_data);

        // 删除购物车中的物品
        db('order_cart')->where(['id' => ['in', $info['cart_ids']]])->delete();

        return suc($res);
    }

    /**
     * 支付未付款订单
     * @param array $info
     *
     * @return json
     */
    public function payNonPaymentOrder($info)
    {
        $field = 'id, out_trade_no, subject, amount, param, status';
        $res = db('order')->field($field)->where(['id' => $info['id'], 'user_id' => $info['user_id']])->find();
        if (!isset($res)) {
            err('', 'ORDER NON');
        }

        # 无效订单
        if ($res['status'] != 1) {
            err('', 'ORDER INVALID');
        }

        # 微信支付参数
        $data = [];
        $data['out_trade_no'] = $res['out_trade_no'];            // 订单号
        $data['subject'] = $res['subject'];                      // 支付标题
        $data['admin_id'] = $info['admin_id'];
        $data['user_id'] = $info['user_id'];
        $data['amount'] = $res['amount'];                        // 总价

        // 不需要创建订单
        $pay_info = ['not_create_order' => 1];

        // 获取微信支付参数
        $weixin = new Weixin();
        $res = $weixin->unifiedOrder($data, $pay_info);

        return suc($res);
    }

    /**
     * 获取订单信息
     * @param array $info
     *      - status            number      状态
     *      - page              number      分页参数
     *
     * @return json
     */
    public function getOrders($info)
    {
        $where = [];
        $where['genre'] = 'goods';

        // status -  1：等待付款， 2：取消付款，3：付款失败，4：付款成功，
        //           20：待发货，21：待收货，22：确认收货，100：全部订单
        if ($info['status'] == 1) {
            $where['status'] = 1;
        } elseif ($info['status'] == 2) {
            $where['status'] = 2;
        } elseif ($info['status'] == 3) {
            $where['status'] = 3;
        } elseif ($info['status'] == 4) {
            $where['status'] = 4;
        } elseif ($info['status'] == 20) {
            $where['status_confirm'] = 1;
        } elseif ($info['status'] == 21) {
            $where['status_confirm'] = 2;
        } elseif ($info['status'] == 22) {
            $where['status_confirm'] = 3;
        } elseif ($info['status'] == 100) {
            $where['status'] = ['<>', 3];
        }

        if (count($where) <= 0) {
            err('', 'STATUS ERROR');
        }

        // 返回订单和商品信息        
        if (isset($info['goods'])) {
            $wheres = [];
            $wheres['o.user_id'] = $info['user_id'];
            $wheres['o.genre'] = 'goods';

            if (isset($where['status'])) {
                $wheres['o.status'] = $where['status'];
            } else {
                $wheres['o.status_confirm'] = $where['status_confirm'];
            }
            $wheres['o.admin_id'] = $info['admin_id'];
            $field = 'o.id, o.out_trade_no, o.amount, o.time_start, o.status, o.status_confirm, o.status_refund,
                o.delivery_amount, o.delivery_name, o.delivery_no, o.delivery_time, o.delivery_receive_time,
                o.addr_name, o.addr_mobile, o.addr_detail, o.invoice_tax, o.invoice_title, o.invoice_content, 
                g.goods_id, g.title, g.subtitle, g.price, g.numbs, g.thumb, g.is_comment';
            $result = db('order')->alias('o')->join('order_goods g', 'o.out_trade_no = g.order_id', 'left')->field($field)
                ->where($wheres)->limit($info['page'], $this->page)->order('id desc')->select();

            // 把商品信息整合到订单下面
            $res = [];
            foreach ($result as $key => $value) {
                if (isset($res[$value['out_trade_no']])) {
                    $count = count($res[$value['out_trade_no']]['goods']);

                    $res[$value['out_trade_no']]['goods'][$count]['goods_id'] = $value['goods_id'];
                    $res[$value['out_trade_no']]['goods'][$count]['title'] = $value['title'];
                    $res[$value['out_trade_no']]['goods'][$count]['subtitle'] = $value['subtitle'];
                    $res[$value['out_trade_no']]['goods'][$count]['price'] = $value['price'];
                    $res[$value['out_trade_no']]['goods'][$count]['numbs'] = $value['numbs'];
                    $res[$value['out_trade_no']]['goods'][$count]['thumb'] = $value['thumb'];
                    $res[$value['out_trade_no']]['goods'][$count]['is_comment'] = $value['is_comment'];
                } else {
                    $res[$value['out_trade_no']] = $value;
                    unset($res[$value['out_trade_no']]['goods_id']);
                    unset($res[$value['out_trade_no']]['title']);
                    unset($res[$value['out_trade_no']]['subtitle']);
                    unset($res[$value['out_trade_no']]['price']);
                    unset($res[$value['out_trade_no']]['numbs']);
                    unset($res[$value['out_trade_no']]['thumb']);
                    unset($res[$value['out_trade_no']]['is_comment']);
                    $res[$value['out_trade_no']]['goods'][0]['goods_id'] = $value['goods_id'];
                    $res[$value['out_trade_no']]['goods'][0]['title'] = $value['title'];
                    $res[$value['out_trade_no']]['goods'][0]['subtitle'] = $value['subtitle'];
                    $res[$value['out_trade_no']]['goods'][0]['price'] = $value['price'];
                    $res[$value['out_trade_no']]['goods'][0]['numbs'] = $value['numbs'];
                    $res[$value['out_trade_no']]['goods'][0]['thumb'] = $value['thumb'];
                    $res[$value['out_trade_no']]['goods'][0]['is_comment'] = $value['is_comment'];
                }
            }

            // 去掉键
            sort($res);

        } else {
            // 只返回订单信息
            $where['user_id'] = $info['user_id'];
            $where['admin_id'] = $info['admin_id'];
            $field = 'id, out_trade_no, amount, time_start, status, status_confirm,
            delivery_amount, delivery_name, delivery_no, delivery_time, delivery_receive_time,
            addr_name, addr_mobile, addr_detail, invoice_tax, invoice_title, invoice_content';
            $res = db('order')->field($field)->where($where)->limit($info['page'], $this->page)->select();

        }
        
        if (empty($res)) {
            suc('', 'ORDER NON');
        }

        suc($res);
    }

    // 获取未评论的商品
    public function getWaitCommentGoods($info)
    {
        $field = 'id, goods_id, order_id, title, subtitle, thumb, price, numbs';
        
        // 0：未付款，1：待发贷，2：已收货，3：退款，4，取消订单
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'is_comment' => 0, 'status' => 2];
        $res = db('order_goods')->field($field)->where($where)->limit($info['page'], $this->page)->select();

        if (empty($res)) {
            suc('', 'GOODS NON');
        }

        foreach ($res as $key => $value) {
            $sign = ['id' => $value['goods_id'], 'sign_key' => $this->signKey, 'sign_time' => $this->timeStamp];
            $res[$key]['sign_code'] = signEncrypt($sign);
            $res[$key]['sign_time'] = $this->timeStamp;
        }

        suc($res);
    }

    // 用户确认收货
    public function abountConfirmReceipt($info)
    {
        $field = 'status, status_confirm';
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'out_trade_no' => $info['order_id']];
        $res = db('order')->field($field)->where($where)->find();

        if (!$res) {
            err('', '无效订单');
        }

        if ($res['status_confirm'] == 3) {
            err('', '已确认收货');
        }

        if ($res['status'] != 4) {
            err('', '未付款');
        }

        if ($res['status_confirm'] != 2) {
            err('', '未发货');
        }

        db('order')->where($where)->update(['status_confirm' => 3]);

        suc();
    }

    // 申请退贷
    public function returnLoan($info)
    {
        $field = 'status, status_confirm, status_refund';
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'out_trade_no' => $info['order_id']];
        $res = db('order')->field($field)->where($where)->find();

        if (!$res) {
            err('', '无效订单');
        }

        if ($res['status_refund'] == 1) {
            err('', '退货申请中...');
        }

        if ($res['status_refund'] == 2) {
            err('', '退货成功');
        }

        if ($res['status'] != 4) {
            err('', '未付款');
        }

        if ($res['status_confirm'] != 3) {
            err('', '未收货');
        }

        db('order')->where($where)->update(['status_refund' => 1, 'refund_mess' => $info['refund_mess']]);

        suc();
    }


    // 申请退贷
    public function returnLoanOrder($info)
    {
        $field = 'status, status_confirm, status_refund';
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'id' => $info['goods_id']];
        $res = db('order_goods')->field($field)->where($where)->find();
        if (!$res) {
            err('', '无效订单');
        }

        if ($res['status_refund'] == 1) {
            err('', '退货申请中...');
        }

        if ($res['status_refund'] == 2) {
            err('', '退货成功');
        }

        if ($res['status'] == 0) {
            err('', '未付款');
        }

        if ($res['status_confirm'] != 3) {
            err('', '未收货');
        }
        $data['status_refund'] = 1;
        $data['status'] = 3;
        $res = db('order_goods')->where($where)->update($data);
        //录入退款数据
        if ($res) {
            db('order_courier')->insert($info);
        }
        suc();
    }

    //客户取消订单 - 华耀德东
    public function order_huayao_del($info)
    {
        $field = 'status, status_confirm, status_refund';
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'id' => $info['goods_id']];
        $res = db('order_goods')->field($field)->where($where)->find();
        if (!$res) {
            err('', '无效订单');
        }
        if ($res['status'] == 1) {
            err('', '待发货不可取消');
        }
        if ($res['status'] == 2) {
            err('', '已收货不可取消订单，可退款');
        }
        if ($res['status'] == 3) {
            err('', '订单已退款');
        }
        $data['status'] = 4;
        $res = db('order_goods')->where($where)->update($data);
        suc();
    }

    // 商户 - 获取订单 - 我购买的其他人的
    public function getMyOrder($info)
    {
        $where = ['o.admin_id' => $info['admin_id'], 'o.user_id' => $info['user_id']];
        $field = 'o.id, o.out_trade_no, o.amount, o.time_start, o.status, o.status_confirm, o.status_refund,
                o.delivery_amount, o.delivery_name, o.delivery_no, o.delivery_time, o.delivery_receive_time,
                o.addr_name, o.addr_mobile, o.addr_detail, o.invoice_tax, o.invoice_title, o.invoice_content, 
                g.goods_id, g.title, g.subtitle, g.price, g.numbs, g.thumb, g.is_comment,g.param,g.create_time';
        $result = db('order')->alias('o')->join('order_goods g', 'o.out_trade_no = g.order_id', 'left')->field($field)
            ->where($where)->limit($info['page'], $this->page)->select();
        $res = [];
        foreach ($result as $key => $value) {
            //获取商品规格信息
            $param = db('param')->where('id=' . $value['param'])->find();
            //dump($param);
            if (isset($res[$value['out_trade_no']])) {

                $count = count($res[$value['out_trade_no']]['goods']);
                $res[$value['out_trade_no']]['goods'][$count]['param'] = $param['key'] . ':' . $param['val'];
                $res[$value['out_trade_no']]['goods'][$count]['goods_id'] = $value['goods_id'];
                $res[$value['out_trade_no']]['goods'][$count]['title'] = $value['title'];
                $res[$value['out_trade_no']]['goods'][$count]['subtitle'] = $value['subtitle'];
                $res[$value['out_trade_no']]['goods'][$count]['price'] = $param['price'];
                $res[$value['out_trade_no']]['goods'][$count]['numbs'] = $value['numbs'];
                $res[$value['out_trade_no']]['goods'][$count]['thumb'] = $value['thumb'];
                $res[$value['out_trade_no']]['goods'][$count]['is_comment'] = $value['is_comment'];
                $res[$value['out_trade_no']]['goods'][$count]['create_time'] = date('Y-m-d G:i:s', $value['create_time']);
            } else {
                $res[$value['out_trade_no']] = $value;
                unset($res[$value['out_trade_no']]['goods_id']);
                unset($res[$value['out_trade_no']]['title']);
                unset($res[$value['out_trade_no']]['subtitle']);
                unset($res[$value['out_trade_no']]['price']);
                unset($res[$value['out_trade_no']]['numbs']);
                unset($res[$value['out_trade_no']]['thumb']);
                unset($res[$value['out_trade_no']]['is_comment']);
                $res[$value['out_trade_no']]['goods'][0]['param'] = $param['key'] . ':' . $param['val'];
                $res[$value['out_trade_no']]['goods'][0]['goods_id'] = $value['goods_id'];
                $res[$value['out_trade_no']]['goods'][0]['title'] = $value['title'];
                $res[$value['out_trade_no']]['goods'][0]['subtitle'] = $value['subtitle'];
                $res[$value['out_trade_no']]['goods'][0]['price'] = $param['price'];
                $res[$value['out_trade_no']]['goods'][0]['numbs'] = $value['numbs'];
                $res[$value['out_trade_no']]['goods'][0]['thumb'] = $value['thumb'];
                $res[$value['out_trade_no']]['goods'][0]['is_comment'] = $value['is_comment'];
                $res[$value['out_trade_no']]['goods'][0]['create_time'] = date('Y-m-d G:i:s', $value['create_time']);
            }
        }

        // 去掉键
        sort($res);
        suc($res);
    }

    // 商户- 获取订单 - 别人购买我的
    public function getShopsOrder($info)
    {
        $where = ['o.admin_id' => $info['admin_id'], 'o.shops_id' => $info['user_id']];
        $field = 'o.id, o.out_trade_no, o.amount, o.time_start, o.status, o.status_confirm, o.status_refund,
                o.delivery_amount, o.delivery_name, o.delivery_no, o.delivery_time, o.delivery_receive_time,
                o.addr_name, o.addr_mobile, o.addr_detail, o.invoice_tax, o.invoice_title, o.invoice_content, 
                g.goods_id, g.title, g.subtitle, g.price, g.numbs, g.thumb, g.is_comment';
        $result = db('order')->alias('o')->join('order_goods g', 'o.out_trade_no = g.order_id', 'left')->field($field)
            ->where($where)->limit($info['page'], $this->page)->select();
        $res = [];
        foreach ($result as $key => $value) {
            if (isset($res[$value['out_trade_no']])) {
                $count = count($res[$value['out_trade_no']]['goods']);

                $res[$value['out_trade_no']]['goods'][$count]['goods_id'] = $value['goods_id'];
                $res[$value['out_trade_no']]['goods'][$count]['title'] = $value['title'];
                $res[$value['out_trade_no']]['goods'][$count]['subtitle'] = $value['subtitle'];
                $res[$value['out_trade_no']]['goods'][$count]['price'] = $value['price'];
                $res[$value['out_trade_no']]['goods'][$count]['numbs'] = $value['numbs'];
                $res[$value['out_trade_no']]['goods'][$count]['thumb'] = $value['thumb'];
                $res[$value['out_trade_no']]['goods'][$count]['is_comment'] = $value['is_comment'];
            } else {
                $res[$value['out_trade_no']] = $value;
                unset($res[$value['out_trade_no']]['goods_id']);
                unset($res[$value['out_trade_no']]['title']);
                unset($res[$value['out_trade_no']]['subtitle']);
                unset($res[$value['out_trade_no']]['price']);
                unset($res[$value['out_trade_no']]['numbs']);
                unset($res[$value['out_trade_no']]['thumb']);
                unset($res[$value['out_trade_no']]['is_comment']);
                $res[$value['out_trade_no']]['goods'][0]['goods_id'] = $value['goods_id'];
                $res[$value['out_trade_no']]['goods'][0]['title'] = $value['title'];
                $res[$value['out_trade_no']]['goods'][0]['subtitle'] = $value['subtitle'];
                $res[$value['out_trade_no']]['goods'][0]['price'] = $value['price'];
                $res[$value['out_trade_no']]['goods'][0]['numbs'] = $value['numbs'];
                $res[$value['out_trade_no']]['goods'][0]['thumb'] = $value['thumb'];
                $res[$value['out_trade_no']]['goods'][0]['is_comment'] = $value['is_comment'];
            }
        }

        // 去掉键
        sort($res);
        suc($res);
    }



    /*
     * 将订单信息分化到商品中
     */
    // 商户 - 获取订单 - 我购买的其他人的   华耀德东新接口
    public function getMyNewOrder($info)
    {
        //直接查询order-goods中的商品信息，前台作为订单信息处理
        $field = ['admin_id', 'user_id'];
        $where['user_id'] = $info['user_id'];
        $where['admin_id'] = $info['admin_id'];
        //查询购买的商品及联查询商品价格
        $res = db('order_goods o')->field($field, true)
            ->order('create_time desc')
            ->where($where)->select();
        foreach ($res as $key => $value) {
            $param = db('param')->field('price')->where('id=' . $value['param'])->find();
            $res[$key]['price'] = $param['price'];
            $res[$key]['create_time'] = date('Y-m-d G:i:s', $value['create_time']);
        }
        //时间戳转换成时间返回

        suc($res);
        die;
    }


    /*
     * 将订单信息分化到商品中
     */
    // 商户 - 获取订单 - 其他人购买我的   华耀德东新接口
    public function getMyNewShop($info)
    {
        $shop_where['user_id'] = $info['user_id'];
        //获得我的商城信息
        $user_shops = db('shops')->field('id')->where($shop_where)->find();
        //直接查询order-goods中的商品信息，前台作为订单信息处理
        $field = ['admin_id', 'user_id'];
        $where['shops_id'] = $user_shops['id'];
        $where['admin_id'] = $info['admin_id'];
        //查询购买的商品及联查询商品价格
        $res = db('order_goods o')->field($field, true)
            ->order('create_time desc')
            ->where($where)->select();
        foreach ($res as $key => $value) {
            $param = db('param')->field('price')->where('id=' . $value['param'])->find();
            $res[$key]['price'] = $param['price'];
            $res[$key]['create_time'] = date('Y-m-d G:i:s', $value['create_time']);
        }
        suc($res);
    }

    /*
     *  商家确认发货
     *  商家 - 确认发货 其他人购买的我的  化德耀东新接口
     */
    public function abountConfirmGo($info)
    {
        $field = 'status, status_confirm';
        $where = ['admin_id' => $info['admin_id'], 'id' => $info['goods_id']];
        $res = db('order_goods')->field($field)->where($where)->find();

        if (!$res) {
            err('', '无效订单');
        }
        //验证商家信息是否正确
        if (db('shops')->where($where)->where('user_id=' . $info['user_id'])->find()) {
            err('', '这不是你的订单');
        }
        if ($res['status_confirm'] == 3) {
            err('', '已确认收货');
        }

        if ($res['status'] == 0) {
            err('', '未付款');
        }
        if ($res['status_confirm'] == 2) {
            err('', '待收货');
        }
        if ($res['status_confirm'] == 3) {
            err('', '已收货');
        }
        //录入发货信息

        unset($info['goods_id']);
        $info['status_confirm'] = 2;
        $info['delivery_time'] = time();
        if (db('order_goods')->where($where)->update($info)) {
            suc('发货成功');
        } else {
            err('', '发货失败，原因:已发货，待收货等');
        }


    }
    /*
     * 华德耀东
     * 用户确认收货
     */
    // 用户确认收货
    public function HuayaoabountConfirmReceipt($info)
    {
        $field = 'status, status_confirm';
        $where = ['admin_id' => $info['admin_id'], 'user_id' => $info['user_id'], 'id' => $info['goods_id']];
        $res = db('order_goods')->field($field)->where($where)->find();
        if (!$res) {
            err('', '无效订单');
        }

        if ($res['status_confirm'] == 3) {
            err('', '已确认收货');
        }

        if ($res['status'] == 0) {
            err('', '未付款');
        }

        if ($res['status_confirm'] != 2) {
            err('', '未发货');
        }
        $data['status_confirm'] = 3;
        $data['status'] = 2;
        db('order_goods')->where($where)->update($data);

        suc();
    }

    /*
     * 华耀德东
     * 支付订单
     */

    public function HuayaopayNonPaymentOrder($info)
    {
        //$field = 'id, out_trade_no, subject, amount, param, status';
        $res = db('order_goods')->where(['id' => $info['id'], 'user_id' => $info['user_id']])->find();
        if (!isset($res)) {
            err('', 'ORDER NON');
        }

        # 无效订单
        if ($res['status'] != 0) {
            err('', 'ORDER INVALID');
        }

        # 微信支付参数
        $data = [];
        $data['out_trade_no'] = $res['order_id'];            // 订单号
        $data['subject'] = '商品支付 - ' . $info['user_id'];                      // 支付标题
        $data['admin_id'] = $info['admin_id'];
        $data['user_id'] = $info['user_id'];
        //获得商品单价
        $price = db('param')->field('price')->where('goods_id=' . $res['goods_id'])->find();

        $data['amount'] = $price['price'] * $res['numbs'];                        // 总价
        // 不需要创建订单
        $pay_info = ['not_create_order' => 1];

        // 获取微信支付参数 
        $weixin = new Weixin();
        $res = $weixin->unifiedOrder($data, $pay_info);
        return suc($res);
    }

    /*
     * 商家确认退款
     */
    public function HuayaoConfirmRetrun($info)
    {
        $field = 'status, status_confirm,status_refund,param,numbs,user_id';
        $where = ['admin_id' => $info['admin_id'], 'id' => $info['goods_id']];
        $res = db('order_goods')->field($field)->where($where)->find();
        if (!$res) {
            err('', '无效订单');
        }
        //验证商家信息是否正确
        if (db('shops')->where($where)->where('user_id=' . $info['user_id'])->find()) {
            err('', '这不是你的订单');
        }
        if ($res['status_confirm'] != 3) {
            err('', '商户未确认收货');
        }

        if ($res['status'] == 0) {
            err('', '未付款');
        }
        if ($res['status_confirm'] == 2) {
            err('', '待收货');
        }
        if ($res['status_refund'] == 2) {
            err('', '已退款');
        }
        if ($res['status'] == 3) {
            err('', '已退款');
        }
        //录入退款信息
        //商家确认退款
        if ($info['return_config']) {
            $data['status_refund'] = 2;
            $data['status'] = 3;
            if (db('order_goods')->where($where)->update($data)) {

                //获得商品支付信息
                $param = db('param')->field('price')->where('id=' . $res['param'])->find();
                $price = $res['numbs'] * $param['price'];
                //返还用户积分
                $user_where['admin_id'] = $info['admin_id'];
                $user_where['id'] = $res['user_id'];
                db('user')->where($user_where)->setInc('commission', $price);
                suc('退款成功');
            } else {
                err('', '发货失败，原因:已发货，待收货等');
            }

        } //商家不退款
        else {
            $data['status_refund'] = 3;
            db('order_goods')->where($where)->update($data);
        }
    }

    /**
     * 农场押金退款
     */

    public function refund($dbAdmin,$dbInfo, $payInfo = [])
    {

        $weixin = new Weixin();

        $weixin->wxPayConfig($dbAdmin);

        require_once VENDOR_PATH . 'Wxpay/lib/WxPay.Api.php';

        # 订单号
        $orderId = date('YmdHis') . $dbInfo . mt_rand(100000, 999999);

        # 获取openid等
        $userinfo = $this->getUserinfo($dbInfo);

        # 查询订单信息
        $where = ['out_trade_no'=>$payInfo['out_trade_no'],'shop_type'=>2, 'status'=>4];
        $order = db('order')->where($where)->order('time_start desc')->find();

        if (!$order) {
            err('', '无交押金记录');
        }

        # 查询订单是否已经退款       
        if ($order['status_refund']==2) {
            err('', '已经退款');
        }

        # 退款
        $input = new \WxPayRefund();
        $input->SetTransaction_id($order['transaction_id']);
        $input->SetTotal_fee($order['amount'] * 100);
        $input->SetRefund_fee($order['amount'] * 100);
        $input->SetOut_refund_no(CUS_WX_MCHID.date("YmdHis"));
        $input->SetOp_user_id(CUS_WX_MCHID);

        $data = \WxPayApi::refund($input);
        // 通信标识
        if ($data['return_code'] != 'SUCCESS') {
            err('', '通信失败');
            
        }
        
        if ($data['result_code'] != 'SUCCESS') {
            err($data, '退款失败');
        }

        //更改订单状态为退款成功
        $where=[];
        $where['user_id'] = $dbInfo;
        $where['admin_id'] = $dbAdmin;
        $where['out_trade_no'] = $order['out_trade_no'];
        db('order')->where($where)->update(['status_refund'=>2]);
        
        //更改退款申请表的退款状态为以处理
        $where=[];
        $where['admin_id'] = $dbAdmin;
        $where['user_id'] = $dbInfo;
        $arr = [];
        $arr['state'] = 1;
        $arr['handle_time'] = time();
        db('farm_refund')->where($where)->update($arr);

        //取消会员等级初始化
        $where=[];
        $where['admin_id'] = $dbAdmin;
        $where['id'] = $dbInfo;
        $str['expire'] = 0;
        $str['grade'] = 1;
        db('user')->where($where)->update($str);
     
        // 生成订单
        $dbInfo = [];
        $dbInfo['openid'] = $userinfo['openid'];
        $dbInfo['out_trade_no'] = $orderId;
        //$dbInfo['partner_trade_no'] = $order['out_trade_no'];
        //$dbInfo['username'] = $userinfo['username'];
        $dbInfo['status_refund'] = 2;
        $dbInfo['shop_type'] = 2;
        $dbInfo['amount'] = $order['amount'];
        $dbInfo['admin_id'] = $order['admin_id'];
        $dbInfo['user_id'] = $order['user_id'];
        $dbInfo['time_start'] = $this->timeStamp;
        $dbInfo['time_expire'] = $this->timeStamp + 1800;
        $dbInfo['subject'] = '农场退押金';
        
        // 返回的数据
        //$dbInfo['result_code'] = $data['result_code'];
        $dbInfo['time_end'] = $this->timeStamp;
        $dbInfo['return_mess'] = json_encode($data);
        
        // 订单信息写入数据库
        $res = db('order')->insert($dbInfo);
        //suc('', '退款成功');
        echo "<script>alert('退款成功');window.history.go(-1);</script>";
        
    }

    /**
     * 获取用户信息
     * @param string $sessionKey
     * @return json
     */
    private function getUserinfo($user_id)
    {
        $result = db('user')->where(['id'=>$user_id])->find();
        
        if (!$result) {
            err('', 'NULL');
        }
        
        return $result;
    }
}
